import 'package:awak/common/utils/util_text.dart';
import 'package:awak/common/utils/util_dialog.dart';
import 'package:awak/common/values/svg.dart';
import 'package:awak/bloc/auth/auth_bloc.dart';
import 'package:awak/bloc/auth/auth_event.dart';
import 'package:awak/bloc/auth/auth_state.dart';
import 'package:awak/common/models/plan.dart';
import 'package:beamer/beamer.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'dart:async';

class DetailPlanPage extends StatefulWidget {
  final Plan? plan;

  const DetailPlanPage({super.key, this.plan});

  @override
  State<DetailPlanPage> createState() => _DetailPlanPageState();
}

class _DetailPlanPageState extends State<DetailPlanPage> {
  Timer? _countdownTimer;
  String _countdownText = '00:00:00';
  Plan? _currentPlan;

  // Delay弹窗的状态变量
  int? _selectedPresetMinutes;
  int _customHours = 0;
  int _customMinutes = 0;

  @override
  void initState() {
    super.initState();
    _currentPlan = widget.plan;
    _startCountdownTimer();
  }

  @override
  void dispose() {
    _countdownTimer?.cancel();
    super.dispose();
  }

  void _startCountdownTimer() {
    _countdownTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (_currentPlan != null && !_currentPlan!.isCompleted) {
        _updateCountdown();
      }
    });
  }

  void _updateCountdown() {
    if (_currentPlan == null) return;

    final now = DateTime.now();
    final difference = _currentPlan!.endTime.difference(now);

    if (difference.isNegative) {
      setState(() {
        _countdownText = '00:00:00';
      });
      return;
    }

    final days = difference.inDays;
    final hours = difference.inHours % 24;
    final minutes = difference.inMinutes % 60;
    final seconds = difference.inSeconds % 60;

    setState(() {
      if (days > 0) {
        _countdownText = '${days}d ${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
      } else {
        _countdownText = '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    if (_currentPlan == null) {
      return Scaffold(
        body: Center(
          child: Text('Plan not found'),
        ),
      );
    }
    return BlocListener<AwakBloc, AwakState>(
      listener: (context, state) {
        if (state is PlanStateUpdated) {
          setState(() {
            _currentPlan = _currentPlan!.copyWith(state: state.state);
          });
        } else if (state is PlanTimeUpdated) {
          setState(() {
            _currentPlan = state.plan;
          });
        }
      },
      child: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
              Color(0xFFD7F349),
              Color(0xFFFFFABA),
            ],
          ),
        ),
        child: Scaffold(
          backgroundColor: Colors.transparent,
          appBar: AppBar(
            backgroundColor: Colors.transparent,
            elevation: 0,
            leading: IconButton(
              icon: Icon(AwakSvg.back, color: Colors.black),
              onPressed: () => Beamer.of(context).beamBack(),
            ),
            title: Text('Current Plan', style: AwakText.titleStyle),
            centerTitle: true,
            actions: [
              Padding(
                padding: EdgeInsets.only(right: 16.w),
                child: Icon(AwakSvg.plan, size: 24.w, color: Colors.black),
              ),
            ],
          ),
          body: SingleChildScrollView(
            padding: EdgeInsets.all(16.w),
            child: Column(
              children: [
                _buildPlanInfo(),
                SizedBox(height: 16.h),
                _buildCountdownContainer(),
                SizedBox(height: 16.h),
                _buildPlanImage(),
                SizedBox(height: 16.h),
                _buildPlanTitle(),
                SizedBox(height: 16.h),
                _buildPlanDescription(),
                SizedBox(height: 40.h),
                _buildActionButtons(),
                SizedBox(height: 40.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildPlanInfo() {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Row(
                children: [
                  Icon(
                    Icons.access_time,
                    size: 20.w,
                    color: Colors.black,
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    'PLAN TIME',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 8.h),
                decoration: BoxDecoration(
                  color: _getStatusColor(),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Text(
                  _getStatusText(),
                  style: AwakText.body14Style.copyWith(
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                    fontSize: 10.sp,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 12.h),
          Text(
            '${_currentPlan!.startTime.year}-${_currentPlan!.startTime.month.toString().padLeft(2, '0')}-${_currentPlan!.startTime.day.toString().padLeft(2, '0')} ${_currentPlan!.startTime.hour.toString().padLeft(2, '0')}:${_currentPlan!.startTime.minute.toString().padLeft(2, '0')} - ${_currentPlan!.endTime.hour.toString().padLeft(2, '0')}:${_currentPlan!.endTime.minute.toString().padLeft(2, '0')}',
            style: AwakText.body14Style.copyWith(
              color: Colors.black,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildCountdownContainer() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color(0xFFD8F34A),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        children: [
          Text(
            'Count Down',
            style: AwakText.body16Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 12.h),
          Text(
            _countdownText,
            style: AwakText.body16Style.copyWith(
              fontWeight: FontWeight.bold,
              color: Colors.black,
              fontSize: 24.sp,
            ),
          ),
        ],
      ),
    );
  }

  Color _getStatusColor() {
    switch (_currentPlan!.state) {
      case 'completed':
        return const Color(0xFFB6F558);
      case 'failed':
        return Colors.red.withValues(alpha: 0.3);
      case 'uncompleted':
      case 'not_started':
      case 'in_progress':
        return const Color(0xFFD8F34A);
      default:
        return Colors.grey.withValues(alpha: 0.3);
    }
  }

  String _getStatusText() {
    switch (_currentPlan!.state) {
      case 'completed':
        return 'Completed';
      case 'failed':
        return 'Failed';
      case 'uncompleted':
        return 'Uncompleted';
      case 'not_started':
        return 'Not Started';
      case 'in_progress':
        return 'In Progress';
      default:
        return 'Unknown';
    }
  }

  Widget _buildPlanImage() {
    return Container(
      width: double.infinity,
      height: 150.h,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12.r),
        child: Image.asset(
          _currentPlan!.picture,
          fit: BoxFit.cover,
        ),
      ),
    );
  }

  Widget _buildPlanTitle() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Plan Title',
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 10.h),
          Text(
            _currentPlan!.title,
            style: AwakText.body14Style.copyWith(
              color: Colors.black,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildPlanDescription() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Description Of The Plan',
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 10.h),
          Text(
            _currentPlan!.description,
            style: AwakText.body14Style.copyWith(
              color: Colors.black,
              fontWeight: FontWeight.w400,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildActionButtons() {
    if (_currentPlan!.state == 'completed') {
      return Container(
        width: double.infinity,
        height: 50.h,
        decoration: BoxDecoration(
          color: const Color(0xFFB6F558),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Center(
          child: Text(
            'Success',
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
        ),
      );
    } else if (_currentPlan!.state == 'failed') {
      return Container(
        width: double.infinity,
        height: 50.h,
        decoration: BoxDecoration(
          color: Colors.red.withValues(alpha: 0.3),
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Center(
          child: Text(
            'Failure',
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.red,
            ),
          ),
        ),
      );
    } else {
      return Row(
        children: [
          Expanded(
            child: GestureDetector(
              onTap: _showFailureDialog,
              child: Container(
                height: 50.h,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    'Failure',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: GestureDetector(
              onTap: _showDelayDialog,
              child: Container(
                height: 50.h,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    'Delay',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          ),
          SizedBox(width: 16.w),
          Expanded(
            child: GestureDetector(
              onTap: _showCompletionDialog,
              child: Container(
                height: 50.h,
                decoration: BoxDecoration(
                  color: const Color(0xFFB6F558),
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    'Completion',
                    style: AwakText.body14Style.copyWith(
                      fontWeight: FontWeight.w600,
                      color: Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      );
    }
  }



  void _showFailureDialog() {
    showAwakDialog(
      context: context,
      title: 'Kindly Reminder',
      description: 'Are you ready to quit now?',
      onCancel: () {},
      onConfirm: () {
        _updatePlanState('failed');
      },
    );
  }

  void _showCompletionDialog() {
    showAwakDialog(
      context: context,
      title: 'Kindly Reminder',
      description: 'Confirm',
      onCancel: () {},
      onConfirm: () {
        _updatePlanState('completed');
      },
    );
  }

  void _showDelayDialog() {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(20.r)),
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (context, setModalState) {
            // 计算最终选择的时间
            int getFinalSelectedMinutes() {
              if (_selectedPresetMinutes != null) {
                return _selectedPresetMinutes!;
              } else {
                return _customHours * 60 + _customMinutes;
              }
            }
            return Container(
              height: 480.h,
              padding: EdgeInsets.all(16.w),
              child: Column(
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      SizedBox(width: 24.w),
                      Text(
                        'DELAY',
                        style: AwakText.body16Style.copyWith(
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Navigator.pop(context),
                        child: Icon(
                          Icons.close,
                          size: 24.w,
                          color: Colors.black,
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 20.h),
                  Expanded(
                    child: GridView.count(
                      crossAxisCount: 3,
                      crossAxisSpacing: 12.w,
                      mainAxisSpacing: 12.h,
                      childAspectRatio: 2.5,
                      children: [
                        _buildDelayOption(15, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                        _buildDelayOption(30, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                        _buildDelayOption(60, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                        _buildDelayOption(120, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                        _buildDelayOption(180, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                        _buildDelayOption(240, _selectedPresetMinutes, (minutes) {
                          setModalState(() {
                            if (_selectedPresetMinutes == minutes) {
                              _selectedPresetMinutes = null;
                            } else {
                              _selectedPresetMinutes = minutes;
                            }
                          });
                        }),
                      ],
                    ),
                  ),
                  SizedBox(height: 20.h),
                  _buildCustomizedTimeSelector(_customHours, _customMinutes, (newHours, newMinutes) {
                    setModalState(() {
                      _customHours = newHours;
                      _customMinutes = newMinutes;
                      _selectedPresetMinutes = null;
                    });
                  }),
                  SizedBox(height: 20.h),
                  GestureDetector(
                    onTap: () {
                      final finalMinutes = getFinalSelectedMinutes();
                      if (finalMinutes > 0) {
                        _delayPlan(finalMinutes);
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      width: double.infinity,
                      height: 50.h,
                      decoration: BoxDecoration(
                        color: const Color(0xFFB6F558),
                        borderRadius: BorderRadius.circular(12.r),
                      ),
                      child: Center(
                        child: Text(
                          'Confirm',
                          style: AwakText.body14Style.copyWith(
                            fontWeight: FontWeight.w600,
                            color: Colors.black,
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(height: 20.h),
                ],
              ),
            );
          },
        );
      },
    );
  }

  Widget _buildCustomizedTimeSelector(int currentHours, int currentMinutes, Function(int, int) onTimeChanged) {
    return Container(
      padding: EdgeInsets.all(16.w),
      decoration: BoxDecoration(
        color: Colors.grey.withValues(alpha: 0.1),
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Customized Time',
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
            ),
          ),
          SizedBox(height: 12.h),
          Row(
            children: [
              Expanded(
                child: _buildTimePickerWheel(
                  'Hours',
                  24,
                  currentHours,
                  (value) {
                    final totalMinutes = value * 60 + currentMinutes;
                    if (totalMinutes <= 1440) {
                      onTimeChanged(value, currentMinutes);
                    }
                  },
                ),
              ),
              SizedBox(width: 16.w),
              Expanded(
                child: _buildTimePickerWheel(
                  'Minutes',
                  60,
                  currentMinutes,
                  (value) {
                    final totalMinutes = currentHours * 60 + value;
                    if (totalMinutes <= 1440) {
                      onTimeChanged(currentHours, value);
                    }
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildTimePickerWheel(String label, int maxValue, int currentValue, Function(int) onChanged) {
    return Column(
      children: [
        Text(
          label,
          style: AwakText.body14Style.copyWith(
            fontWeight: FontWeight.w500,
            color: Colors.grey[600],
            fontSize: 12.sp,
          ),
        ),
        SizedBox(height: 8.h),
        Container(
          height: 80.h,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.r),
          ),
          child: ListWheelScrollView.useDelegate(
            controller: FixedExtentScrollController(initialItem: currentValue),
            itemExtent: 30.h,
            perspective: 0.005,
            diameterRatio: 1.2,
            physics: FixedExtentScrollPhysics(),
            onSelectedItemChanged: onChanged,
            childDelegate: ListWheelChildBuilderDelegate(
              childCount: maxValue,
              builder: (context, index) {
                final isSelected = index == currentValue;
                return Center(
                  child: Text(
                    index.toString().padLeft(2, '0'),
                    style: AwakText.body14Style.copyWith(
                      fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                      color: isSelected ? Colors.black : Colors.grey,
                      fontSize: isSelected ? 16.sp : 14.sp,
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildDelayOption(int minutes, int? selectedMinutes, Function(int) onSelect) {
    final isSelected = minutes == selectedMinutes;
    String displayText;
    if (minutes < 60) {
      displayText = '$minutes Minutes';
    } else {
      final hours = minutes ~/ 60;
      displayText = '$hours Hours';
    }

    return GestureDetector(
      onTap: () {
        onSelect(minutes);
      },
      child: Container(
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xFFD8F34A) : Colors.grey.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(8.r),
        ),
        child: Center(
          child: Text(
            displayText,
            style: AwakText.body14Style.copyWith(
              fontWeight: FontWeight.w600,
              color: Colors.black,
              fontSize: 12.sp,
            ),
          ),
        ),
      ),
    );
  }

  void _updatePlanState(String newState) {
    context.read<AwakBloc>().add(UpdatePlanStateEvent(_currentPlan!.id!, newState));
    setState(() {
      _countdownText = '00:00:00';
    });
    _resetDelayState();
  }

  void _resetDelayState() {
    _selectedPresetMinutes = null;
    _customHours = 0;
    _customMinutes = 0;
  }

  void _delayPlan(int minutes) {
    final newEndTime = _currentPlan!.endTime.add(Duration(minutes: minutes));
    final updatedPlan = _currentPlan!.copyWith(endTime: newEndTime);

    context.read<AwakBloc>().add(UpdatePlanTimeEvent(updatedPlan));
  }
}
